<?php

namespace App\Service\OpenShop\FeishuMini;

use App\Http\Middleware\OpenShop\WangGuiCityByPower;
use App\Service\BaseService;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Http;

class CommonService extends BaseService
{
    public static function getCityByLngAndLat($lng, $lat, $haveAdcode, $haveCity)
    {
        $adcode  = 0;
        if (!$lng || !$lat) {
            return [
                'name'   => $haveCity[0] ?? '',
                'adcode' => $haveAdcode[0] ?? 0
            ];
        }
        $key     = WangGuiCityByPower::getRandomAmapKey();
        $areaRes = Http::withHeaders(['Content-Type' => 'application/json; charset=utf-8'])
            ->get(config('area.geocodeRegeo'), [
                'key'      => $key,
                'location' => $lng . ',' . $lat,
            ])
            ->json();
        if ($areaRes['status'] == 1 && isset($areaRes['regeocode']['addressComponent']['citycode'])) {
            $city = $areaRes['regeocode']['addressComponent']['city'] == [] ? $areaRes['regeocode']['addressComponent']['province'] : $areaRes['regeocode']['addressComponent']['city'];
        } else {
            $city = '';
        }
        $cityRes = Http::withHeaders(['Content-Type' => 'application/json; charset=utf-8'])
            ->get(config('area.getAreaByName'), [
                'keywords'    => $city,
                'subdistrict' => 1,
                'key'         => $key,
            ])
            ->json();
        $haveName = '';
        if ($cityRes['status'] == 1 && count($cityRes['districts'])) {
            foreach ($cityRes['districts'] as $tempCity) {
                if ($tempCity['adcode'] == ($haveAdcode[0] ?? 0)) {
                    $haveName = $tempCity['name'];
                }
                if ($tempCity['level'] == 'province') {
                    //市级行政区
                    foreach ($tempCity['districts'] as $lowerCity) {
                        if ($lowerCity['adcode'] == ($haveAdcode[0] ?? 0)) {
                            $haveName = $lowerCity['name'];
                        }
                        if ($lowerCity['level'] != 'city') {
                            continue;
                        }
                        $adcode = $lowerCity['adcode'];
                    }
                }

                if ($tempCity['level'] != 'city') {
                    continue;
                }
                $adcode = $tempCity['adcode'];
            }
        }
        if (in_array($adcode, $haveAdcode)) {
            return [
                'name'   => str_replace('城区', '', $city),
                'adcode' => $adcode
            ];
        } else {
            return [
                'name'   => str_replace('城区', '', $haveName),
                'adcode' => $haveAdcode[0] ?? 0
            ];
        }
    }
}
